function simpleTick(fn) {
  return setTimeout(fn, 30);
}
function isSameSecond(time1, time2) {
  return Math.floor(time1 / 1000) === Math.floor(time2 / 1000);
}
function formatTime(time) {
  const SECOND = 1000;
  const MINUTE = 60 * SECOND;
  const HOUR = 60 * MINUTE;
  const DAY = 24 * HOUR;
  const hours = Math.floor(time / HOUR);
  const minutes = Math.floor((time % HOUR) / MINUTE);
  const seconds = Math.floor((time % MINUTE) / SECOND);
  const milliseconds = Math.floor(time % SECOND);
  return {
    hours: hours<10?`0${hours}`:hours,
    minutes: minutes < 10 ? `0${minutes}` : minutes,
    seconds: seconds < 10 ? `0${seconds}` : seconds,
    milliseconds
  };
}
export default class CountDown {
  /**
   * 
   * @param {endTime} 必须为date对象
   */
  constructor({endTime, leftTimeChange, tag}) {
    this.leftTime = null;
    this.timer = null;
    this.endTime = endTime;
    this.remain = -1;
    this.leftTimeChange = leftTimeChange;
    this.tag = tag;
  }
  fire() {
    if (this.endTime instanceof Date) {
      this.macroTick();
    } else {
      console.error('endTime must be a Date Obj');
    }
  }
  macroTick() {
    this.timer = simpleTick(() => {
      const remain = this.getRemain();
      if (!isSameSecond(remain, this.remain) || remain === 0) {
        this.setRemain(remain);
      }
      if (this.remain !== 0) {
        this.macroTick();
      }
    });
  }
  clear() {
    if (!this.timer) {
      return;
    }
    clearTimeout(this.timer);
    this.timer = null;
  }
  getRemain() {
    return Math.max(this.endTime - Date.now(), 0);
  }
  setRemain(remain) {
    this.remain = remain;
    this.leftTime = formatTime(remain);
    if (typeof(this.leftTimeChange) == 'function') {
      this.leftTimeChange({
        leftTime: this.leftTime,
        tag: this.tag
      });
    }
  }
}